<template>

<div class="lar-table">

    <!--按钮组-->
    <el-button-group class="table--button-group" >

            <el-button @click="showSearch=!showSearch" class="simple-button"  icon="el-icon-search"></el-button>
            <el-button @click="getData()"  class="simple-button" icon="el-icon-refresh"></el-button>
            <!--<el-button  plain size="small" icon="el-icon-edit">编辑</el-button>-->
            <el-button @click="delMultiRows()" class="simple-button" plain   icon="el-icon-delete" ></el-button >
    </el-button-group>
    <h3 class="table--title">{{title}}</h3>

    <!--{{fullApi}}-->
    <!--搜索盒子-->
    <transition name="fade">
        <lar-search-box :model="model" :schemas="searchSchemas" :pipeName="pipeName" v-show="showSearch">
        </lar-search-box>
    </transition>

    <!--数据表单-->
    <el-table
            :data="tableData"
            v-loading="loading"
            :border="true"
            highlight-current-row
            show-overflow-tooltip
            @selection-change="handleSelectionChange"
            @sort-change="handleSort"
            style="width: 100%">
            >
        <!--id的列-->
        <el-table-column
                :sort-change="handleSort"
                type="selection"
                width="55">
        </el-table-column>
        <!--数据的列-->
        <template v-for="schema in Schemas.fields">
            <el-table-column
                    sortable
                    :prop="schema.key"
                    :label="schema.name"
                    :width="schema | result('td_width','')"
            >
            <template slot-scope="scope">
                <lar-table-ceil v-if="schema"
                        :data ="scope.row"
                        :schema = "schema"
                        :action="'table'"
                        @quick-change="quickChange($event,schema.key,scope.row)"
                >
                </lar-table-ceil>
            </template>
            </el-table-column>
        </template>
        <!--操作的列-->
        <el-table-column class-name="action-th"
                         align="right"
                         header-align="center"
                         :render-header="actionRender"
                         v-if="Schemas.config"
                         style="height:100px;"
                         :width="Object.keys(Schemas.config.action).length*76">
            <template slot-scope="scope">
                <template style="text-align: right"  v-for="action in Schemas.config.action">
                <el-button
                        round
                        size="mini"
                        :type="action.type"
                        @click="handleAction(scope.$index, scope.row,action)">
                    {{action.html}}
                </el-button>
                </template>
            </template>
        </el-table-column>

    </el-table>
    <div class="block" style="text-align: right">
        <br />
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageInfo.current_page"
                :page-sizes="[10,20, 40, 60, 80]"
                :page-size="pageInfo.per_page"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageInfo.total">
        </el-pagination>
    </div>
</div>

</template>

<script>

    export default {
        props:{
          model:{
              type:String,
          }
        },
        data() {
            return {
                title:'数据管理',
                tableData: [],
                multipleSelection:[],
                api:'',
                pageInfo:{
                    per_page:10,
                    total:0,
                    current_page:1,
                },
                apiQuery:{},//查询的参数
                Schemas:[],
                showSearch:false,
                loading:true,
                searchQueryCache:{
                    data:{},
                    time:0,
                },
                canQuickChange:false,//是否全部加载完成了
            }
        },

        created: function () {
            this.getSchemas();
        },
        computed: {
            dataRefreshEvents () {
                return this.$store.getters.getRefreshEvents(this.model);
            },
            searchQuery () {
                let query = {};
                let data = this.$store.getters.getPipe(this.pipeName);
                return this.$larfree.getSearchQuery(data);

            },
            pipeName(){
                return this.Schemas.pipeName?this.Schemas.pipeName:this.model+'.table';
            },
            searchSchemas:function () {
                if(!this.Schemas)
                    return [];
                return this.Schemas['search'];
            },
            fullApi:function() {
                let query=this.apiQuery;
                query['pageSize']=this.pageInfo.per_page*1;
                query['page']=this.pageInfo.current_page;
                query = Object.assign(query, this.searchQuery);
                return this.$larfree.httpQuery(query,this.api);
            },
        },

        watch:{
            model:function (newValue,oldValue) {
                this.getSchemas();
            },
//            tableData:{
//                handler(newName, oldName) {
//                    console.log(newName);
//                },
//                deep: true
//            },
            dataRefreshEvents:function(){
                this.loading=true;
                this.getData();
            },
            //如果api变化就请求数据
            fullApi:function(newQuestion){
                this.loading=true;
                this.getData();
            },
        },

        methods: {
            //获取配置
            getSchemas(){
                if(!this.model)
                    return '';
                this.loading=true;
                this.$http.get('/system/component/'+this.model+'/base.table',{  ttl: 3600 })
                .then((response)=>{
                    this.loading=false;
                    if(response.data.status==1) {

                        this.Schemas = response.data.data;;
                        this.api = response.data.data.config.api;

                        this.tableData=[];
                    }else{
                        this.$message.error('Table模块错误');
                    }
                })
                .catch((error)=>{
                    this.loading=false;
                    this.$message.error('Table模块错误');
                    // console.log(error);
                });
            },
            //渲染操作列
            actionRender(h){
                //如果有操作权限
                if(this.Schemas.config.button.add)
                    return <span>操作<span class="add_button"  onClick={this.add}>
                                <span>
                                    <i class="el-icon-plus"></i>
                                </span>
                            </span></span>;
                else
                    return <span>操作</span>;
            },
            //处理下action的触发时间
            handleAction(index,data,action){
                // this.$debug.log(action);

                if(action.url){
                    let url = this.$larfree.replaceParm(action.url,data);
                    this.$debug.log(url,'actionUrl',this);
                    this.$router.push({ path: url })
                }else if(action.action){
                    let func = this.$larfree.replaceParm(action.action,data);
                    action.real_api = this.$larfree.replaceParm(action.api,data);
                    this[func](index,data,action);
                }
            },

            //第一列选中
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            handleSizeChange(val) {
                this.pageInfo.per_page=val;
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page=val;
            },
            handleSort(column){
                let sort='desc';
                if(column.order=='ascending')
                     sort='asc';
                Vue.set(this.apiQuery,'@sort',column.column.property+'.'+sort);
            },
            //批量删除
            delMultiRows(){
                this.$confirm('是否删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //读取操作按钮中的删除操作 如果没有 说明不能删除
                    let delAction = this.Schemas.config.action.filter((item)=>{
                            if(item.action == 'delRows')
                                return item;
                    })
                    if(delAction.length<1){
                        this.$message.error('无权删除');
                        return false;
                    }
                    delAction = delAction[0];
                    this.multipleSelection.forEach((item)=> {
                        let api = this.$larfree.replaceParm(delAction.api, item);
                        this.$http.delete(api).then((response) => {
                            if (response.data.status == 1) {
                                this.getData();
                            } else {
                                this.$message.error(response.data.msg);
                            }
                        }).catch(() => {
                            this.$message.error('删除失败:网络错误');
                        })
                    })
                }).catch(() => {

                });
            },
            //直接删除
            delRows(index,data,action){
                this.$confirm('是否删除'+data.id+'?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then((data) => {
                    this.$http.delete(action.real_api).then((response) => {
                        if (response.data.status == 1) {
                            this.getData();
                        } else {
                            this.$message.error(response.data.msg);
                        }
                    }).catch(() => {
                        this.$message.error('删除失败:网络错误');
                    })
                }).catch(() => {
                    //取消
                });
            },
            //添加
            add(){
                this.$router.push({ path: this.Schemas.config.button.add.url })
            },
            //获取数据
            getData(){
                this.loading=true;
                this.canQuickChange=false;
                this.$http.get( this.fullApi )
                .then( (response)=>{
                    this.loading=false;
//                    this.debug.log(response.data.data,this.api);
                    this.tableData = response.data.data;
                    this.pageInfo  = response.data.mate;

                    //让他全部加载完了才能开始
                    setTimeout(()=>{
                        this.canQuickChange=true;
                    },2000)
                })
                .catch( (error)=> {
                    this.$message.error('请求数据错误');
                });

            },

            /**
             * 快速修改
             * @param $event
             * @param key
             * @param data
             */
            quickChange($event,key,data){
                if(this.canQuickChange){
                    let newValue = $event['newValue'];
                    this.$debug.log(this.Schemas);
                    let url = this.$larfree.replaceParm(this.Schemas.config.quick_change_api,data);
                    let putData={};
                    putData[key]=newValue;
                    this.$http.put( url ,putData )
                        .then( (response)=>{
                            if(response.data.status==1){
                                this.$message.success(response.data.msg);
                            }else{
                                this.$message.error(response.data.msg);
                            }
                        });
                }
            },
        }
    }
</script>
<style scoped>

    .table--title{
        padding-top: 5px;
    }
    .simple-button:hover{
        color:#409EFF !important;
    }
    .table--button-group{
        float: right !important;
        margin-bottom: 20px;
    }
    .table--button-group button {
        font-size: 24px !important;
    }

</style>
<style >
    .lar-table .el-table{
        border: none;
    }
    .lar-table .el-table--border td, .lar-table .el-table--border th{
        border-right:none ;
    }
    .action-th .cell{
        padding: 0;
    }

    .table--button-group .el-button{

        padding:0px 10px;
    }
    .simple-button{
        background: none !important;
        border: none;
    }

    /*.action-th .cell,*/
    /*.el-table__footer-wrapper, .el-table__header-wrapper,*/
    /*.action-th{*/
        /*overflow:visible !important;*/
    /*}*/

    .add_button{
        position: relative;
    }
    .add_button span{
        font-size:24px;
        background: #ec407a;
        color:white;
        line-height: 46px;
        width:44px;
        height:44px;
        top:-12px;
        position: absolute;
        text-align: center;
        border-radius: 30px;
        cursor: pointer;
        box-shadow: 0 0 7px #aaa;
        z-index: 99;
        margin-left: 10px;
        ransform:rotate(0deg);
        transition: box-shadow,transform 2s;

    }
    .add_button span:hover{
        transform:rotate(360deg);
        box-shadow: 0 0 10px #888888;
        transition: box-shadow,transform 2s;
    }
    .el-table .cell, .el-table th div{
        overflow: initial !important;
    }

</style>